<template>
  <div>
    <a-modal
      :visible="visible"
      title="新建剪辑"
      :bodyStyle="{
        padding: '20px 60px',
      }"
      :width="800"
      :footer="null"
      :closable="false"
      :keyboard="false"
      :maskClosable="false"
      @cancel="cancelClick"
    >
      <a-form :label-col="{ span: 4 }">
        <a-form-item label="剪辑名称" v-bind="validateInfos.title">
          <a-input
            v-model:value="modelRef.title"
            placeholder="请输入剪辑名称"
          />
        </a-form-item>
        <a-form-item
          label="关联项目"
          v-bind="validateInfos.merchant_library_id"
        >
          <a-select
            style="width: 502px"
            v-model:value="modelRef.merchant_library_id"
            show-search
            :filter-option="false"
            :not-found-content="fetching ? undefined : null"
            placeholder="请选择关联项目素材库，点击生成成片，系统自动保存成片结果"
            :options="libraryList"
            @change="libraryChange"
            @search="librarySearch"
            allowClear
          >
            <template v-if="fetching" #notFoundContent>
              <a-spin size="small" />
            </template>
          </a-select>
          <a-button
            type="primary"
            style="
              background: #2878FF;
              border: none;
              border-top-right-radius: 6px;
              border-bottom-right-radius: 6px;
            "
            @click="addMerchant"
            >新建</a-button
          >
        </a-form-item>
        <a-form-item
          label="成片保存至"
          v-bind="validateInfos.merchant_folder_statck_id"
        >
          <div @click="backChange">
            <a-select
              :open="backOpen"
              v-model:value="modelRef.merchant_folder_statck_id"
              allowClear
              placeholder="请先选择关联项目"
              :options="searchList"
              :disabled="!modelRef.merchant_library_id"
              @select="backOpen = false"
            >
              <!-- @search="folderStatckSearch"
            @change="folderStatckChange" -->
              <template #dropdownRender="{ menuNode: menu }">
                <div ref="searchRef">
                  <div style="padding: 5px 10px">
                    <a-input v-model:value="searchValue" placeholder="请输入">
                      <template #addonBefore>
                        <SearchOutlined />
                      </template>
                    </a-input>
                  </div>
                  <a-divider style="margin: 4px 0" />
                  <v-nodes :vnodes="menu" />
                </div>
              </template>
            </a-select>
          </div>

          <!-- <a-select
            v-model:value="modelRef.merchant_folder_statck_id"
            allowClear
            show-search
            placeholder="请先选择关联项目"
            :options="savePiecesOptions"
            :disabled="!modelRef.merchant_library_id"
            :not-found-content="fetching ? undefined : null"
            :filter-option="false"
            @search="folderStatckSearch"
            @change="folderStatckChange"
          >
            <template #dropdownRender="{ menuNode: menu }">
              <v-nodes :vnodes="menu" />
            </template>
            <template v-if="fetching" #notFoundContent>
              <a-spin size="small" />
            </template>
          </a-select> -->
        </a-form-item>
        <a-form-item label="选择比例" v-bind="validateInfos.proportion">
          <a-row class="proportion-list" :gutter="[16, 16]">
            <a-col @click="proportionClick('9:16')">
              <div
                class="list"
                :class="modelRef.aspect_ratio == '9:16' ? 'list-border' : ''"
              >
                <div class="sub-box1">
                  <div>竖版</div>
                  <div>9:16</div>
                </div>
              </div>
            </a-col>
            <a-col @click="proportionClick('16:9')">
              <div
                class="list"
                :class="modelRef.aspect_ratio == '16:9' ? 'list-border' : ''"
              >
                <div class="sub-box2">
                  <div>横版</div>
                  <div>16:9</div>
                </div>
              </div>
            </a-col>
            <a-col @click="proportionClick('1:1')">
              <div
                class="list"
                :class="modelRef.aspect_ratio == '1:1' ? 'list-border' : ''"
              >
                <div class="sub-box3">
                  <div>方形</div>
                  <div>1:1</div>
                </div>
              </div>
            </a-col>
          </a-row>
        </a-form-item>
      </a-form>
      <div class="footer">
        <a-space>
          <a-button
            ghost
            type="primary"
            style="border: 1px solid #e0e0e6; color: #000; border-radius: 6px"
            @click="cancelClick"
            >取消</a-button
          >
          <a-button
            type="primary"
            style="background: #2878FF; border: none; border-radius: 6px"
            @click="submitClick"
            :loading="loading"
            >开始剪辑</a-button
          >
        </a-space>
      </div>
    </a-modal>

    <!-- 新建项目 -->
    <NewMerchant
      :visible="visibleMerchant"
      @onCancel="onCancelMerchant"
      @onSubmit="onSubmit"
    />

    <!-- 弹框登录 -->
    <ShotstackLoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />
  </div>
</template>

<script>
import { computed, reactive, ref, toRefs, watch } from "vue";
import { Form, message } from "ant-design-vue";
import store from "@/store";
import NewMerchant from "../../MaterialCenter/modules/NewMerchant.vue";
import utils from "../../../../common/utils/utils";
import { useRoute, useRouter } from "vue-router";
import request from "../../../../common/utils/request";
import { SearchOutlined } from "@ant-design/icons-vue";
import { onClickOutside } from "@vueuse/core";

const useForm = Form.useForm;
export default {
  name: "NewClip",
  components: {
    NewMerchant,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    SearchOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props, { emit }) {
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      count: 0,
      savePiecesOptions: [],
      loading: false,
      visibleMerchant: false,
      loginVisible: false,
      libraryList: [],
      fetching: false,
      searchValue: "",
      backOpen: false,
    });

    const modelRef = reactive({
      title: "",
      merchant_library_id: undefined,
      merchant_folder_statck_id: undefined,
      aspect_ratio: "9:16",
      unique_id: "",
    });

    const searchRef = ref(null);

    onClickOutside(searchRef, (e) => {
      state.backOpen = false;
      state.searchValue = "";
    });

    const searchList = computed(() =>
      state.savePiecesOptions.filter((item) =>
        item?.label?.includes(state.searchValue)
      )
    );
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      reactive({
        title: [
          {
            required: true,
            message: "请输入剪辑名称",
          },
        ],
        merchant_library_id: [
          {
            required: true,
            message: "请关联项目",
          },
        ],
        merchant_folder_statck_id: [
          {
            required: true,
            message: "请先选择关联项目",
          },
        ],
        proportion: [
          {
            required: true,
            message: "请先选择比例",
          },
        ],
      })
    );

    const proportionClick = (key) => {
      modelRef.aspect_ratio = key;
    };

    const addMerchant = () => {
      state.visibleMerchant = true;
    };
    const onCancelMerchant = () => {
      state.visibleMerchant = false;
    };

    const cancelClick = () => {
      resetFields();
      emit("onCancel");
    };

    const submitClick = () => {
      validate().then(() => {
        utils.checkLogin().then((isLogin) => {
          if (!isLogin) {
            state.loginVisible = true;
            return;
          }
          let params = {
            edit_model: props.data.editModel,
            ...modelRef,
          };
          state.loading = true;
          request
            .post("/work_ai", "/user/shotstack/clip/creative", params)
            .then((res) => {
              state.loading = false;
              window.open(
                `${window.location.origin}/#/editingCenter?title=${params.title}&aspect_ratio=${params.aspect_ratio}&edit_model=${params.edit_model}&id=${res.id}&merchant_library_id=${modelRef.merchant_library_id}&merchant_folder_statck_id=${modelRef.merchant_folder_statck_id}&comeFrom=${props.data.comeFrom}`
              );
              emit("onSubmit");
            })
            .catch(() => {
              state.loading = false;
            });
        });
      });
    };

    const loginCallback = () => {
      router.go(0);
    };
    let timer = null;
    const folderStatckSearch = (text) => {
      if (text) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        getLibrarySelect(modelRef.merchant_library_id, text);
      }, 600);
    };

    const getLibrarySelect = (merchant_library_id, keyword) => {
      request
        .get("/work_ai", "/user/shotstack/folder/select/list", {
          folder_type: props.data.type || "video",
          merchant_library_id,
          keyword,
        })
        .then((res) => {
          state.savePiecesOptions = res.result.map((item) => {
            return {
              label: item.folder_name,
              value: item.id,
            };
          });
          if (state.savePiecesOptions?.length > 0) {
            modelRef.merchant_folder_statck_id =
              state.savePiecesOptions[0].value;
          }
        });
    };

    const folderStatckChange = (key) => {
      if (!key) {
        getLibrarySelect(modelRef.merchant_library_id, "");
      }
    };

    const libraryChange = (key) => {
      modelRef.merchant_folder_statck_id = "";
      if (!key) {
        getLibraryList("");
      }
      getLibrarySelect(key);
    };

    const getLibraryList = (name) => {
      state.fetching = true;
      request
        .get("/work_ai", "/user/shotstack/library/list", {
          page: 1,
          pageSize: 10000000,
          name,
        })
        .then((res) => {
          state.libraryList = res.result.data.map((item) => {
            return {
              label: item.name,
              value: item.id,
            };
          });
          state.fetching = false;
        });
    };

    const librarySearch = (text) => {
      if (text) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        getLibraryList(text);
      }, 600);
    };

    const onSubmit = () => {
      onCancelMerchant();
      getLibraryList();
    };

    const getUniqueId = () => {
      request.get("/work_ai", "/user/platform/uniqueId").then((res) => {
        modelRef.unique_id = res.uniqueId;
      });
    };

    const init = () => {
      getLibraryList();
      getUniqueId();
    };

    const backChange = (e) => {
      e.preventDefault();
      if (state.backOpen) {
        state.searchValue = "";
      }
      state.backOpen = !state.backOpen;
    };

    const getPopupContainer = () => {
      return document.getElementById("searchList");
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
        }
      }
    );

    return {
      ...toRefs(state),
      validateInfos,
      modelRef,
      cancelClick,
      submitClick,
      proportionClick,
      addMerchant,
      onCancelMerchant,
      loginCallback,
      onSubmit,
      libraryChange,
      librarySearch,
      folderStatckSearch,
      folderStatckChange,
      backChange,
      searchList,
      searchRef,
      getPopupContainer,
    };
  },
};
</script>

<style lang="less" scoped>
.footer {
  width: 100%;
  text-align: center;
}

.proportion-list {
  .list {
    width: 145px;
    height: 80px;
    border: 1px solid #e6e6e6;
    border-radius: 5px;
    display: flex;
    align-items: center;
    cursor: pointer;

    .sub-box1 {
      margin: 0 auto;
      width: 40px;
      height: 70px;
      border: 1px solid #2878FF;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #2878FF;
      background: linear-gradient(225deg, #eef7ff 0%, #b2dfe9 100%);
    }
    .sub-box2 {
      margin: 0 auto;
      width: 88px;
      height: 50px;
      border: 1px solid #2878FF;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #2878FF;
      background: linear-gradient(225deg, #eef7ff 0%, #b2dfe9 100%);
    }
    .sub-box3 {
      margin: 0 auto;
      width: 50px;
      height: 50px;
      border: 1px solid #2878FF;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #2878FF;
      background: linear-gradient(225deg, #eef7ff 0%, #b2dfe9 100%);
    }
    &.list-border {
      border: 1px solid #2878FF;
      background: #eef7ff;
    }
  }
}
</style>
